package com.suliao.common.core;

import cn.hutool.json.JSONUtil;
import com.suliao.common.base.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author： M1nG
 * @since： 2020/9/22 17:06
 * @description： 全局Controller增强
 * @version： 1.0
 */
@RestControllerAdvice
public class GlobalResultHandler /*implements ResponseBodyAdvice<Object>*/ {

    // todo  swagger 兼容处理 + swagger  升级3.0


 /*   //判断支持的类型
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 判断为null构建Result对象进行返回
        if (o == null) {
            return Result.success(null);
        }
        // 判断是Result子类或其本身就返回Object o本身，因为有可能是接口返回时创建了Result,这里避免再次封装
        if (o instanceof Result) {
            return (Result<Object>) o;
        }
        // String特殊处理，否则会抛异常
        if (o instanceof String) {
            return JSONUtil.toJsonStr(Result.success(o));
        }
        return Result.success(o);
    }*/

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        e.printStackTrace();
        return Result.error(e.getMessage() == null ? e.toString() : e.getMessage());
    }

    @ExceptionHandler({RuntimeException.class})
    public Result runtimeExceptionHandler(RuntimeException ex) {
        ex.printStackTrace();
        return Result.error(ex.getMessage() == null ? ex.toString() : ex.getMessage());
    }

}
